import { login, logout, getInfo ,phoneSmsCodeLogin} from '@/api/user'
import { getToken, setToken, removeToken } from '@/utils/auth'
import { resetRouter, constantRoutes } from '@/router'
import router from '@/router'

const getDefaultState = () => {
  return {
    token: getToken(),
    name: '',
    avatar: '',
    // 管理员身份
    userRole: '',
    // 权限数组
    permissionList: [],
    // 真实权限路由
    resultAsyncRouter: [],
    // 组件权限名称
    treesId: []
  }
}

const state = getDefaultState()

// 两个路由数组进行对比，对比显示当前用户该显示的路由权限
const computedAsyncRouters = (constantRoutes, routers) => {

  let newArr = routers.map(item => {
    return item.componentName;
  })
  return constantRoutes.filter(item => {
    if (newArr.indexOf(item.name) != -1) {
      if (item.children && item.children.length) {
        item.children = computedAsyncRouters(item.children, routers)
      }
      return true;
    }
  })
}

const mutations = {
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
  SET_TOKEN: (state, token) => {

    state.token = token
  },
  SET_NAME: (state, name) => {
    state.name = name
  },
  SET_AVATAR: (state, avatar) => {
    state.avatar = avatar
  },
  SET_USERROLE: (state, userRole) => {
    state.userRole = userRole
  },
  SET_PERMISSIONLIST: (state, permissionList) => {
    state.permissionList = permissionList
  },
  // 获取路由权限组件名称
  SET_TREESID: (state, treesId) => {
    console.log(treesId, '路由');
    state.treesId = treesId
  },
  // 最终计算的异步路由
  SET_RESULTASYNCROUTER: (state, asyncRouters) => {
    state.resultAsyncRouter = asyncRouters
    // 给路由器添加新的路由
    router.addRoutes(state.resultAsyncRouter)
  },
  RESET_STATE: (state) => {
    Object.assign(state, getDefaultState())
  },
}

const actions = {
  // 登录
  async login({ commit }, userInfo) { 
    console.log(commit, '用户名')
    // if(userInfo.phone){
    //   const { smsCode, smsToken, phone } = userInfo

    //   let res=await phoneSmsCodeLogin({smsCode,smsToken,phone})
    // }else{
      // const { username, password, imageCode,imageToken } = userInfo
     
      let res = await login(userInfo)
      
    // }
    if (res.code == 200) {

        commit('SET_TOKEN', res.data.sessionToken)
        setToken(res.data.sessionToken)
        // console.log(res, "用户名");
        localStorage.setItem("id", res.data.id);
        return 'ok'
      } else {
        return Promise.reject(new Error('faile'));
      }
  },

  // get user info
  async getInfo({ commit, state }) {
    let res = await getInfo(state.token)
    console.log(res, '用户信息');
    return new Promise((resolve, reject) => {
       
      getInfo(state.token).then(response => {
        const { data } = response
        console.log('============data', state.token)
        if (!data) {
          return reject('Verification failed, please Login again.')
        }

        const { name, headimgurl, userRole, permissionList } = data

        let treesId = permissionList.map(item => {
          return item.componentName;
        })
        // console.log(data)

        // localStorage.setItem('adv_session_token', state.token)
        commit('SET_NAME', name)
        commit('SET_AVATAR', headimgurl)
        commit('SET_USERROLE', userRole)
        commit('SET_PERMISSIONLIST', permissionList)
        commit('SET_TREESID', treesId)
        commit('SET_RESULTASYNCROUTER', computedAsyncRouters(constantRoutes, permissionList))
        resolve(data)
      }).catch(error => {
        console.log(error, '=============')
        reject(error)
      })
    })
  },

  // user logout
  logout({ commit, state }) {
    commit('RESET_STATE');
    // return new Promise((resolve, reject) => {
    //   logout(state.token).then(() => {
    //     removeToken() // must remove  token  first
    //     resetRouter()
    //     commit('RESET_STATE')
    //     resolve()
    //   }).catch(error => {
    //     reject(error)
    //   })
    // })
  },

  // remove token
  resetToken({ commit }) {
    return new Promise(resolve => {
      removeToken() // must remove  token  first
      commit('RESET_STATE')
      resolve()
    })
  }
}

export default {
  namespaced: true,
  state,
  mutations,
  actions
}

